<template>
  <div class="edit-task">
    <h2>编辑事项</h2>
    <form @submit.prevent="submitForm">
      <label for="name">名称:</label>
      <input type="text" id="name" v-model="task.name" required>
      <label for="completed">完成状态:</label>
      <select id="completed" v-model="task.completed">
        <option :value="true">已完成</option>
        <option :value="false">未完成</option>
      </select>
      <button type="submit">保存</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      task: {
        id: null,
        name: '',
        completed: false
      }
    };
  },
  created() {
    // 获取事项ID
    const taskId = this.$route.params.taskId;
    // 根据事项ID获取事项信息
    this.fetchTask(taskId);
  },
  methods: {
    fetchTask(taskId) {
      const token = localStorage.getItem('token');
      axios.get(`/api/edit-task/${taskId}`, {
        headers: {
          'Authorization': token
        }
      })
      .then(response => {
        this.task = response.data;
      })
      .catch(error => {
        this.$message.error('获取事项信息失败');
      });
    },
    submitForm() {
      const token = localStorage.getItem('token');
      const taskId = this.task.id;
      const updatedTask = {
        name: this.task.name,
        completed: this.task.completed
      };

      axios.put(`/api/edit-task/${taskId}/edit`, updatedTask, {
        headers: {
          'Authorization': token
        }
      })
      .then(response => {
        this.$message.success('事项编辑成功');
        this.$router.push('/task-list');
      })
      .catch(error => {
        this.$message.error('事项编辑失败');
      });
    }
  }
};
</script>

<style scoped>
.edit-task {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 10px;
}

input[type="text"],
select {
  width: 100%;
  padding: 6px 10px;
  border-radius: 4px;
  border: 1px solid #ccc;
}

button[type="submit"] {
  margin-top: 20px;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>